package com.fablesoft.projectdatacollect.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.authentication.asynctask.AsyncParseSFZ;
import com.authentication.utils.ToastUtil;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.album.ImageItem;
import com.fablesoft.projectdatacollect.album.ShowAllPhotoActivity;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.EducationListResponse;
import com.fablesoft.projectdatacollect.bean.IDCardNewBean;
import com.fablesoft.projectdatacollect.bean.IdCardResultResponse;
import com.fablesoft.projectdatacollect.bean.PersonTypeListResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.http.HttpUploadFilesThread;
import com.fablesoft.projectdatacollect.util.BitmapUtil;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.DateUtil;
import com.fablesoft.projectdatacollect.util.FileUtils;
import com.fablesoft.projectdatacollect.util.Log4jUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android_serialport_api.ParseSFZAPI;

public class FragmentIdCard extends BaseFragment implements RadioGroup.OnCheckedChangeListener {

    private TextView nameValue;
    private TextView sexValue;
    private TextView nationValue;
    private TextView yearValue;
    private TextView monthValue;
    private TextView dayValue;
    private TextView addressValue;
    private TextView idNumValue;
    private TextView signDepartmentValue;
    private TextView expiryDateValue;
    private ImageView ivIdPhoto;
    private TextView readResult;
    private RadioGroup rgPhoto;
    private ImageView ivPhoto;

    private Bitmap headImageThumb;
    private byte[] idImage;
    private String sceneImagePath;
    private List<File> idImages;
    private List<String> filenames;

    private AsyncParseSFZ asyncParseSFZ;
    private IDCardNewBean cardInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_identity_info, container, false);
        initView();
        initData();
        setSerialPort(true);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        setSerialPort(false);
    }

    @Override
    protected void initView() {
        super.initView();
        nameValue = (TextView) view.findViewById(R.id.name_value);
        sexValue = (TextView) view.findViewById(R.id.sex_value);
        nationValue = (TextView) view.findViewById(R.id.nation_value);
        yearValue = (TextView) view.findViewById(R.id.year_value);
        monthValue = (TextView) view.findViewById(R.id.month_value);
        dayValue = (TextView) view.findViewById(R.id.day_value);
        addressValue = (TextView) view.findViewById(R.id.address_value);
        idNumValue = (TextView) view.findViewById(R.id.id_num_value);
        signDepartmentValue = (TextView) view.findViewById(R.id.sign_department_value);
        expiryDateValue = (TextView) view.findViewById(R.id.expiry_date_value);
        ivIdPhoto = (ImageView) view.findViewById(R.id.id_photo);
        readResult = (TextView) view.findViewById(R.id.read_result);
        rgPhoto = (RadioGroup) view.findViewById(R.id.rg_photo);
        ivPhoto = (ImageView) view.findViewById(R.id.iv_take_photo);
        btNext = (Button) view.findViewById(R.id.next1);
        rgPhoto.setOnCheckedChangeListener(this);
        ivPhoto.setOnClickListener(this);
        btNext.setOnClickListener(this);
        ivPhoto.setClickable(false);
    }

    @Override
    protected void initData() {
        super.initData();
        idImages = new ArrayList<>();
        filenames = new ArrayList<>();
    }

    @Override
    public void onClick(View v) {
        if (isRepeatClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.next1:
                submitIdCardInfo();
                break;
            case R.id.iv_take_photo:
                if (cardInfo == null) {
                    ToastUtil.showToast(mContext, "请先读卡！");
                    return;
                }
                Intent intent = new Intent(mContext,
                        ShowAllPhotoActivity.class);
                intent.putExtra("count", 1);
                startActivityForResult(intent, CommonUtils.IMAGE_OPEN);
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId) {
            case R.id.rb_id_photo:
                ivPhoto.setClickable(false);
                ivPhoto.setImageResource(R.drawable.icon_take_photo_unchecked);
                break;
            case R.id.rb_scene:
                ivPhoto.setClickable(true);
                if (headImageThumb == null) {
                    ivPhoto.setImageResource(R.drawable.icon_take_photo_checked);
                } else {
                    ivPhoto.setImageBitmap(headImageThumb);
                }
                break;
        }
    }

    @Override
    public void setSerialPort(boolean enable) {
        if (enable) {
            asyncParseSFZ = new AsyncParseSFZ(MyApplication.getInstance().getHandlerThread()
                    .getLooper(), MyApplication.getInstance().getRootPath(), mContext);

            asyncParseSFZ.setOnReadSFZListener(new AsyncParseSFZ.OnReadSFZListener() {
                @Override
                public void onReadSuccess(ParseSFZAPI.People people) {
                    Log.d("sglei-card", "asyncParseSFZ, onReadSuccess, people = " + people.getPeopleIDCode());
                    updateInfo(people);
                    readResult.setText(R.string.read_success);
                    mHandler.sendEmptyMessageDelayed(CommonUtils.SFZ_CODE, 1000);
                }

                @Override
                public void onReadFail(int confirmationCode) {
                    Log.d("sglei-card", "asyncParseSFZ, onReadFail, confirmationCode = " + confirmationCode);
                    if (confirmationCode == ParseSFZAPI.Result.FIND_FAIL) {
                        Log.i("luzx", "身份证未寻到卡,有返回数据");
                    } else if (confirmationCode == ParseSFZAPI.Result.TIME_OUT) {
                        Log.i("luzx", "身份证未寻到卡,无返回数据，超时！！");
                    } else if (confirmationCode == ParseSFZAPI.Result.OTHER_EXCEPTION) {
                        Log.i("luzx", "身份证可能是串口打开失败或其他异常");
                    } else if (confirmationCode == ParseSFZAPI.Result.NO_THREECARD) {
                        Log.i("luzx", "身份证此二代证没有指纹数据");
                    }
                    mHandler.sendEmptyMessageDelayed(CommonUtils.SFZ_CODE, 1000);
                }
            });
            mHandler.sendEmptyMessage(CommonUtils.SFZ_CODE);
        } else {
            mHandler.removeMessages(CommonUtils.SFZ_CODE);
            if (asyncParseSFZ != null) {
                asyncParseSFZ.removeCallbacksAndMessages(null);
            }
        }
    }

    private void updateInfo(ParseSFZAPI.People people) {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (cardInfo == null) {
            cardInfo = new IDCardNewBean();
        }
        mediaPlayer = MediaPlayer.create(mContext, R.raw.beep);
        mediaPlayer.start();
        addressValue.setText(people.getPeopleAddress());
        dayValue.setText(people.getPeopleBirthday().substring(6));
        idNumValue.setText(people.getPeopleIDCode());
        signDepartmentValue.setText(people.getDepartment());
        expiryDateValue.setText(DateUtil.insertStr(people.getStartDate(), CommonUtils.DOT) + CommonUtils.LINE + DateUtil.insertStr(people.getEndDate(), CommonUtils.DOT));
        monthValue.setText(people.getPeopleBirthday().substring(4, 6));
        nameValue.setText(people.getPeopleName());
        nationValue.setText(people.getPeopleNation());
        sexValue.setText(people.getPeopleSex());
        yearValue.setText(people.getPeopleBirthday().substring(0, 4));
        if (people.getPhoto() != null && isAdded()) {
            Bitmap photo = BitmapFactory.decodeByteArray(people.getPhoto(), 0,
                    people.getPhoto().length);
            ivIdPhoto.setImageDrawable(new BitmapDrawable(getResources(), photo));
        }

        cardInfo.setAddress(people.getPeopleAddress());
        cardInfo.setName(people.getPeopleName());
        cardInfo.setBirthday(DateUtil.insertStr(people.getPeopleBirthday(), CommonUtils.LINE));
        cardInfo.setIdNo(people.getPeopleIDCode());
        cardInfo.setIssueUnit(people.getDepartment());
        cardInfo.setNation(people.getPeopleNation());
        idImage = people.getPhoto();
        if ("男".equals(people.getPeopleSex())) {
            cardInfo.setSex("1");
        } else if ("女".equals(people.getPeopleSex())) {
            cardInfo.setSex("2");
        }
        cardInfo.setValidPeriod(expiryDateValue.getText().toString());
        btNext.setVisibility(View.VISIBLE);
    }

    public void submitIdCardInfo() {
        if (cardInfo == null || TextUtils.isEmpty(cardInfo.getIdNo())) {
            ToastUtil.showToast(mContext, "请读卡！");
            return;
        }
        btNext.setClickable(false);
        String filename;
        idImages.clear();
        filenames.clear();
        if (idImage != null) {
            filename = "sfz_idCard_" + System.currentTimeMillis() + ".jpg";
            filenames.add(filename);
            idImages.add(FileUtils.byteToFile(idImage, imagePath, filename));
        }
        if (!TextUtils.isEmpty(sceneImagePath)) {
            filename = "sfz_photo_" + System.currentTimeMillis() + ".jpg";
            filenames.add(filename);
            idImages.add(BitmapUtil.pathToFile(sceneImagePath));
        }
        Map<String, Object> uploadFileparams = new HashMap<>();
        uploadFileparams.put("name", cardInfo.getName());
        uploadFileparams.put("address", cardInfo.getAddress());
        uploadFileparams.put("validPeriod", cardInfo.getValidPeriod());
        uploadFileparams.put("nation", cardInfo.getNation());
        uploadFileparams.put("issueUnit", cardInfo.getIssueUnit());
        uploadFileparams.put("sex", cardInfo.getSex());
        uploadFileparams.put("birthday", cardInfo.getBirthday());
        uploadFileparams.put("idNo", cardInfo.getIdNo());
        mActivity.idNo = cardInfo.getIdNo();

        HttpUploadFilesThread thread = new HttpUploadFilesThread(Config.UPLOAD_IDCARD_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = CommonUtils.UPLOAD_ID_CARD_IMAGE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                        mActivity.onNotLogin(response);
                    }
                }, idImages, filenames, uploadFileparams, IdCardResultResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(thread);
    }

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CommonUtils.SFZ_CODE:
                    asyncParseSFZ.readSFZ(ParseSFZAPI.SECOND_GENERATION_CARD);
                    break;
                case CommonUtils.UPLOAD_ID_CARD_IMAGE:
                    IdCardResultResponse response = (IdCardResultResponse) msg.obj;
                    mActivity.result = response;
                    if (response == null) {
                        Toast.makeText(mContext,
                                R.string.request_error, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!response.getSuccess() && response.getCode().equals("personExist")) {
                        readResult.setText(response.getMessage());
                        btNext.setVisibility(View.INVISIBLE);
                        return;
                    }
                    readResult.setText(response.getMessage());
                    btNext.setVisibility(View.VISIBLE);
                    btNext.setClickable(true);
                    listener.onNext(1);
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == CommonUtils.IMAGE_OPEN) {
            if (ShowAllPhotoActivity.tempSelectBitmap == null || ShowAllPhotoActivity.tempSelectBitmap.size() <= 0) {
                ToastUtil.showToast(mContext, "请选择图片！");
                return;
            }
            ImageItem item = ShowAllPhotoActivity.tempSelectBitmap.get(0);
            showScenePhoto(item.getImagePath());
        }
    }

    private void showScenePhoto(String path) {
        Log.d(CommonUtils.TAG_UPLOAD, "path = " + path);
        headImageThumb = BitmapUtil.decodeThumbBitmapForFile(path, 125, 104);
        ivPhoto.setImageBitmap(headImageThumb);
        sceneImagePath = path;
    }
}
